//
//  ADViewController.m
//  MagazineShangejie
//
//  Created by mac on 15/1/19.
//  Copyright (c) 2015年 CnbizMedia. All rights reserved.
//

#import "ADViewController.h"
#import "Util.h"
//#import "MMDrawerController.h"
#import "MainTabBarController.h"
#import "SlideTableViewController.h"
#import "ArticleViewController.h"
#import "TableViewController.h"
#import "ADWebViewController.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#import "Util.h"
@interface ADViewController (){
    NSDictionary*AD_Dict;
    MainTabBarController*MainTabBar;
    NSString *AdvertisementWebsite;
    NSString *ADShowOrHidden;
    int *ADShowOrHiddenNumber;
    NSDictionary*dict1;
    NSString *IPString;
    
    NSMutableArray *Subscribe;
    NSMutableArray *IndexArray;
}
@property (weak, nonatomic) IBOutlet UIWebView *ADWebView;
@property (weak, nonatomic) IBOutlet UIButton *CloseButton;

//@property (nonatomic,strong) MMDrawerController * drawerController;
@property (strong, nonatomic) IBOutlet UILabel *longitude;
@property (strong, nonatomic) IBOutlet UILabel *latitude;

@property (strong, nonatomic) IBOutlet UILabel *location;
@property (strong, nonatomic) CLLocationManager *locationManager;
@end

@implementation ADViewController
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _ADWebView.hidden = YES;
    _CloseButton.hidden =YES;
            IPString = @"60.195.250.90";
    if ([UserDefaults objectForKey:@"IP"]) {
        IPString = [UserDefaults objectForKey:@"IP"];
    }
    
    NSLog(@"保存到单例的IPString %@",IPString);

//    [self getTheAllCity];
    //广告网页和关闭按钮先隐藏
    
    
 
    
    
    
    
    //每次初始化程序都要把精选加到这个数组里
    Subscribe = [[NSMutableArray alloc] init];
    IndexArray = [[NSMutableArray alloc] init];
    NSDictionary*dict=[NSDictionary dictionaryWithObjectsAndKeys:@"精选",@"catname",@"",@"catdir", nil];
    
//    [Subscribe insertObject:dict atIndex:0];
//    
//    
//    [UserDefaults setValue:Subscribe forKey:@"listTop"];
    
    
    CountdownTime = 3;//广告时间
    _CountdownLabel.text =  [NSString stringWithFormat:@"%d", CountdownTime ];
    _CountdownLabel.hidden = YES;
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    UIImageView*imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-self.view.frame.size.width/3.8787, self.view.frame.size.width, self.view.frame.size.width/3.8787)];
    imageview.image=[UIImage imageNamed:@"openD"];
    [self.view addSubview:imageview];

    [self loadNews];

    NSURL *baseURL = [NSURL URLWithString:@"http://adm.kanshangjie.com"];

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
    [manager GET:@"/v1/List" parameters:@{@"appId": @"7",@"appSecret":@"93377492c0ecc88b",@"dev":@"1"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [UserDefaults setObject:responseObject forKey:@"ad"];
        NSDictionary*dic = responseObject[@"data"][@"alist"];
        NSLog(@"dic ---+++=== %@",dic);
//        NSArray *arr = [dic[@"name"] componentsSeparatedByString:@"|"];
        
//        NSLog(@"arr [1] == %@",arr[1]);
//        NSLog(@"arr all %@",arr);
        
        
        NSURL*url;
        for (NSDictionary*dic in responseObject[@"data"][@"alist"]) {
            if ([dic[@"type"] integerValue]==1) {
                url=[NSURL URLWithString:dic[@"typeval"]];
                AD_Dict=dic;
                AdvertisementWebsite = dic[@"adlink"];
                NSLog(@"AdvertisementWebsite %@",AdvertisementWebsite);
                CountdownTime = [dic[@"jumptime"] intValue];
                
                //新增 timeflag ，判断是否显示倒计时，1为显示，2为不显示
                if ([dic[@"timeflag"] integerValue]==2) {
                    _CountdownLabel.hidden = YES;
                    _pushButton.hidden     = YES;
                }
            }
        }
        
        
        
        //获取广告图片
        UIImageView*imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height*0.83)];
        [self.view addSubview:imageview];
        [imageview sd_setImageWithPreviousCachedImageWithURL:url andPlaceholderImage:nil options:SDWebImageRefreshCached progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            [imageview setImage:image];
            [self performSelector:@selector(MainVC) withObject:nil afterDelay:3];//倒计时，执行这个方法
        }];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"operation == %@",operation);
        NSLog(@"error == %@",error);
        
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];

    
    
    
    //倒计时
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod) userInfo:nil repeats:YES];
    
    
    //添加手势
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    
    [_AdvertisementToWebView addGestureRecognizer:singleTap];
    
    
    //接收通知的设置,广告显示完毕，跳转到主界面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MainVC) name:@"showTheNews" object:nil];//都是nil

}

//手势的执行
-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer
{
   
    if (AdvertisementWebsite) {
//        [[ UIApplication sharedApplication] openURL:[ NSURL URLWithString:AdvertisementWebsite]];
        
        NSURL *url = [[NSURL alloc]initWithString:AdvertisementWebsite];
        
        
        
        [UserDefaults setValue:AdvertisementWebsite forKey:@"AdvertisementWebsite"];
        
        UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        
 
        
        
        ADWebViewController*login=[story instantiateViewControllerWithIdentifier:@"ADWebViewController"];
        UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:nil];
        
//        [self performSelector:@selector(MainVC) withObject:nil afterDelay:1];//倒计时，执行这个方法
        [self MainVC];
//        [_ADWebView loadRequest:[NSURLRequest requestWithURL:url]];
        
//        _ADWebView.hidden = NO;
//        _CloseButton.hidden = NO;

    }
   
}

- (IBAction)clouseEvent:(id)sender {
    
    _ADWebView.hidden = YES;
    _CloseButton.hidden = YES;
    [self MainVC];
  
}


//倒计时
- (void)timerFireMethod
{
    
    _CountdownLabel.text = [NSString stringWithFormat:@"%d",--CountdownTime];
    if (CountdownTime == 0) {
        [self MainVC];
    }

}

-(void)loadNews{
 
    
    dict1 = [[NSDictionary alloc] init];
  
    NSURL *url = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo2.php?ip=myip"];
    
    
    NSURL *baseURL = [NSURL URLWithString:@"http://ip.taobao.com/"];
    
    
    //首先获取IP地址
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager GET:@"service/getIpInfo2.php" parameters:@{@"ip": @"myip"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *IPDic = responseObject[@"data"];
        
        IPString = IPDic [@"ip"];
        NSLog(@"淘宝获取到的IPString == %@",IPString);
        [UserDefaults setValue:IPString forKey:@"IP"];
   
    
 
        
        //然后将精选和本地加入到条目中
        //获取的是喜欢的新闻类的列表
//    [[AppAPIClient sharedClient] GET:@"Category/Subscribe" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        
//        NSLog(@"responseObject -=-=-=-=-==-=-== %@",responseObject);
//        
//        if (![responseObject[@"data"] isKindOfClass:[NSArray class]]){
//            return ;
//        }
//        Subscribe = [responseObject[@"data"] mutableCopy];
//        NSDictionary*dict=[NSDictionary dictionaryWithObjectsAndKeys:@"精选",@"catname",@"",@"catdir", nil];
//        
//        if (dict1.count != 0) {
////            [Subscribe insertObject:dict1 atIndex:1];
//        }
//        
//        [Subscribe insertObject:dict atIndex:0];
// 
//        
////        [UserDefaults setValue:Subscribe forKey:@"listTop"];
////        NSLog(@"UserDefaults == %@",UserDefaults);
////        NSLog(@"Subscribe == %@",Subscribe);
//        
//        //设置通知，城市已经切换，现在刷新界面
////        [[NSNotificationCenter defaultCenter] postNotificationName:@"showTheNewCity" object:self userInfo:nil ];
//
//        if (IPString.length == 0) {
////             IPString = @"113.204.112.162";
//        }
        
//        IPString = @"218.28.191.50";//郑州
//        60.195.250.90  //北京
//        IPString = @"";
//        IPString = @"60.195.250.90";
        

        
        if (IPString.length > 1) {
            //如果ip不为空才去获取城市列表
            [self getTheAllCity];
        }
        
        NSLog(@"获取的是全部的新闻列表的IPString == %@",IPString);
        //获取的是全部的新闻列表
        [[AppAPIClient sharedClient] GET:@"Category/Index" parameters:@{@"localip": IPString} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            IndexArray = responseObject[@"data"] ;
            NSLog(@"IndexArray -- %@",IndexArray);
            
            
            
           
            
            if([IndexArray isKindOfClass:[NSNull class]] || [IndexArray count] == 0){
                return;
            }
            NSMutableArray*listBottom=[IndexArray mutableCopy];
//             NSMutableArray*listBottom=[[NSMutableArray alloc] init];
            NSMutableArray *allArray = [IndexArray mutableCopy];
            NSLog(@"服务器获取的全部数据 listBottom == %@  %lu",listBottom,(unsigned long)listBottom.count);
            NSMutableArray *listTop=[NSMutableArray arrayWithArray:[UserDefaults objectForKey:@"listTop"]];

            NSLog(@"保存本地的订阅栏目 listTop == %@  %lu",listTop,(unsigned long)[listTop count]);
//            [listBottom addObjectsFromArray:responseObject[@"data"]];
            for (NSDictionary*dic in [UserDefaults objectForKey:@"listTop"]) {
                for (NSDictionary*_dic in listBottom) {
                    if ([dic[@"catname"] isEqualToString:_dic[@"catname"]]) {
                        NSLog(@"_dic %@",_dic);
                        [listBottom removeObject:_dic];
                        break;
                    }
                }
                
            }
            [UserDefaults setValue:listBottom forKey:@"listBottom"];
            NSLog(@"listBottom == %@",listBottom);
//            [SVProgressHUD dismiss];
            
           
            
            
         

            
            //当用户在没有开通本地栏目的地区，默认加入一个精选
            NSDictionary*dict=[NSDictionary dictionaryWithObjectsAndKeys:@"精选",@"catname",@"",@"catdir", nil];
//            [UserDefaults setValue:dict forKey:@"local"];
            
            
            NSLog(@"allArray +=+ %@",allArray);
            for (NSMutableDictionary * cityDic in allArray ) {
                
                     NSLog(@"cityDic +=+ %@",cityDic);
                    if ([[cityDic objectForKey:@"description"] isEqualToString:@"local"]) {
                    
                    NSDictionary *dic = listTop[0];
                    NSDictionary *dicCity = listTop[1];
                        NSLog(@"dicCity --== %@",dicCity);
                    
                    if (![dic[@"catname"] isEqualToString:@"精选"]) {
                        [listTop insertObject:dict atIndex:0];
                    }
                    if (![dicCity[@"description"] isEqualToString:@"local"]) {
                        [listTop insertObject:dict atIndex:0];
                        
//                        [listTop removeObject:cityDic];
//                        [listTop insertObject:cityDic atIndex:1];
//                        [UserDefaults setValue:listTop forKey:@"listTop"];
//                        [listBottom removeObject:cityDic];
//                        [UserDefaults setValue:listBottom forKey:@"listBottom"];
                        
                        NSLog(@"listTop -=-= %@",listTop);
                        
                    }
                        
//                        [UserDefaults setValue:cityDic forKey:@"local"];
                        NSLog(@"the cityDic is %@",cityDic);
                    
//                    NSMutableArray*listTop=[IndexArray mutableCopy];
                    
//                    [listTop setObject:cityDic atIndexedSubscript:1];//将这个城市的字典排在数组的第2位
                    
                    
                }
            }
            
            for (NSMutableDictionary * theCityDic in listBottom ) {
                
                NSLog(@"theCityDic +=+ %@",theCityDic);
                if ([[theCityDic objectForKey:@"description"] isEqualToString:@"local"]) {
                      [listBottom removeObject:theCityDic];
                      [UserDefaults setValue:listBottom forKey:@"listBottom"];
                    
                    NSLog(@"listBottom %@",listBottom);
                    
                    //                    NSMutableArray*listTop=[IndexArray mutableCopy];
                    
                    //                    [listTop setObject:cityDic atIndexedSubscript:1];//将这个城市的字典排在数组的第2位
                    
                    
                }
            }
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"ERR: %@",operation.responseString);
            NSLog(@"ERR:error %@",error);
        }];
    }
     
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];

        
    
//    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"ERR: %@",operation.responseString);
//        
//    }];
    
        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//        NSLog(@"operation == %@",operation);
//        NSLog(@"error == %@",error);
//        
//        [SVProgressHUD showErrorWithStatus:@"网络错误"];
//    }];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}
///*
-(void)setPush_dic:(NSDictionary *)Push_dic{
    TableViewController*table=(TableViewController*)[MainTabBar.customizableViewControllers[0] topViewController];
    table.push_dic=Push_dic;
}
//*/

-(void)MainVC{
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];

    if(MainTabBar != nil){
        if(self.Push_dic!=nil){
            TableViewController*table=(TableViewController*)[MainTabBar.viewControllers[0] topViewController];
//            ArticleViewController*ar=[story instantiateViewControllerWithIdentifier:@"ArticleViewController"];
            //[self presentViewController:ar animated:YES completion:nil];
            //[self.drawerController.centerViewController presentViewController:ar animated:YES completion:nil];
//            table.push_dic=self.Push_dic;
            [self presentViewController:MainTabBar animated:YES completion:^{table.push_dic=self.Push_dic;
            }];
            return;
        }else{
            [self presentViewController:MainTabBar animated:YES completion:nil];
        }
    }
    

//    SlideTableViewController*slide=[story instantiateViewControllerWithIdentifier:@"SlideTableViewController"];
    MainTabBar=[story instantiateViewControllerWithIdentifier:@"MainTabBarController"];
//    self.drawerController = [[MMDrawerController alloc]
//                             initWithCenterViewController:MainTabBar
//                             leftDrawerViewController:nil
//                             rightDrawerViewController:slide];
//    [self.drawerController setRestorationIdentifier:@"MMDrawer"];
//
//    
//    [self.drawerController setMaximumRightDrawerWidth:self.view.frame.size.width*0.6];
//    
//    [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
//    
//    [self.drawerController
//     setDrawerVisualStateBlock:^(MMDrawerController *drawerController, MMDrawerSide drawerSide, CGFloat percentVisible) {
//         MMDrawerControllerDrawerVisualStateBlock block;
//         
//         if(block){
//             block(drawerController, drawerSide, percentVisible);
//         }
//     }];
    
    self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (IBAction)JumpToNextView:(id)sender {
    
    [self MainVC];
}



- (void)getTheAllCity
{
//    [UserDefaults objectForKey: @"IP"]
    NSLog(@"获取城市列表的IPString == %@",IPString);
    [[AppAPIClient sharedClient] GET:@"Local/List" parameters:@{@"ip": IPString} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"++++ responseObject ++++ %@",responseObject);
        
        if ([responseObject [@"code"] integerValue] == 1) {
            
        
            NSMutableArray *cityArray = [NSMutableArray  arrayWithArray:responseObject[@"data"] [@"cities"] ];
            NSLog(@"++++ cityArray ++++ %@",cityArray);
            
            NSMutableArray *firstArray = [[NSMutableArray alloc] init];
            
            NSMutableDictionary *cityNameDic = [[NSMutableDictionary alloc] init];
            for (  cityNameDic in cityArray ) {
                
                NSString  *catName = cityNameDic[@"catname"];
                [firstArray addObject:catName];
            }
            
            
    //        cityArray = [NSArray arrayWithArray:firstArray];
            
            NSLog(@"++++ cityArray ++++ %@",firstArray);
            [UserDefaults setObject:firstArray forKey:@"allCityNameArray"];
            [UserDefaults setObject:cityArray forKey:@"cityNameArray"];
             }
            
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        
    }];
   
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [self presentViewController:[[MainTabBarController alloc] init] animated:YES completion:NULL];
}





@end
